import type { CanvasComponent } from '../stores/designStore';
import { cloneDeep } from 'lodash-es';

/**
 * 组件增强工具
 * 提供统一的组件处理逻辑，用于预览和导出功能
 */
export class ComponentEnhancer {
  /**
   * 增强组件数据以便渲染
   * 确保按钮等组件有正确的文本和样式
   * @param components 组件列表
   * @returns 增强后的组件列表
   */
  static enhanceComponentsForRendering(components: any[]): any[] {
    if (!components || !Array.isArray(components)) {
      console.warn('enhanceComponentsForRendering: components不是数组或为空');
      return [];
    }

    // 深拷贝组件数据，避免修改原始数据
    const clonedComponents = cloneDeep(components);

    // 确保组件按照正确的顺序渲染
    return clonedComponents.map((comp, index) => {
      if (!comp) {
        console.warn('enhanceComponentsForRendering: 组件为空');
        return null;
      }

      const enhancedComp = { ...comp };
      
      // 确保有type属性
      if (!enhancedComp.type) {
        console.warn('组件缺少type属性，设置为默认div');
        enhancedComp.type = 'div';
      }
      
      // 确保有id属性
      if (!enhancedComp.id) {
        enhancedComp.id = 'comp-' + Date.now() + '-' + Math.floor(Math.random() * 10000);
        console.warn(`组件缺少id属性，生成临时id: ${enhancedComp.id}`);
      }
      
      // 确保有props对象
      enhancedComp.props = enhancedComp.props || {};
      
      // 处理不同类型的组件
      switch (enhancedComp.type) {
        case 'el-button':
          // 确保按钮有文本
          if (!enhancedComp.props.text && !enhancedComp.props.label) {
            enhancedComp.props.text = enhancedComp.props.content || '按钮';
          }
          
          // 确保按钮有类型
          if (!enhancedComp.props.type) {
            enhancedComp.props.type = 'primary';
          }
          
          // 确保按钮有尺寸
          if (!enhancedComp.props.size) {
            enhancedComp.props.size = 'default';
          }
          break;
          
        case 'el-input':
          // 确保输入框有占位符
          if (!enhancedComp.props.placeholder) {
            enhancedComp.props.placeholder = '请输入...';
          }
          
          // 确保有默认值
          if (enhancedComp.props.value === undefined && enhancedComp.props.modelValue === undefined) {
            enhancedComp.props.value = '';
          }
          break;
          
        case 'el-select':
          // 确保下拉框有占位符
          if (!enhancedComp.props.placeholder) {
            enhancedComp.props.placeholder = '请选择';
          }
          
          // 确保有选项数据
          if (!enhancedComp.props.options || !Array.isArray(enhancedComp.props.options) || enhancedComp.props.options.length === 0) {
            enhancedComp.props.options = [
              { value: 'option1', label: '选项1' },
              { value: 'option2', label: '选项2' }
            ];
          }
          break;
          
        case 'el-radio':
        case 'el-checkbox':
          // 确保单选框或复选框有标签
          if (!enhancedComp.props.label) {
            enhancedComp.props.label = '选项' + (Math.floor(Math.random() * 10) + 1);
          }
          
          // 修复样式，设置为auto而非100%
          if (enhancedComp.style) {
            enhancedComp.style.width = 'auto';
            enhancedComp.style.height = 'auto';
            enhancedComp.style.position = 'relative';
            enhancedComp.style.display = 'flex';
            enhancedComp.style.alignItems = 'center';
          }
          break;
          
        case 'el-radio-group':
        case 'el-checkbox-group':
          // 确保单选/复选框组有选项数据
          if (!enhancedComp.props.options || !Array.isArray(enhancedComp.props.options) || enhancedComp.props.options.length === 0) {
            enhancedComp.props.options = [
              { value: 'option1', label: '选项1' },
              { value: 'option2', label: '选项2' }
            ];
          }
          
          // 为单选框组设置默认选中值
          if (enhancedComp.type === 'el-radio-group' && enhancedComp.props.value === undefined && enhancedComp.props.modelValue === undefined) {
            enhancedComp.props.value = enhancedComp.props.options[0].value;
          }
          
          // 为复选框组设置默认选中值
          if (enhancedComp.type === 'el-checkbox-group' && enhancedComp.props.value === undefined && enhancedComp.props.modelValue === undefined) {
            enhancedComp.props.value = [enhancedComp.props.options[0].value];
          }
          
          // 对子组件进行样式处理，设置自动宽高布局
          if (enhancedComp.children && enhancedComp.children.length > 0) {
            enhancedComp.children.forEach((child: any) => {
              if ((child.type === 'el-radio' || child.type === 'el-checkbox') && child.style) {
                child.style.width = 'auto';
                child.style.height = 'auto';
                child.style.position = 'relative';
                child.style.display = 'flex';
                child.style.alignItems = 'center';
                // 清除可能导致布局问题的样式属性
                delete child.style.zIndex;
              }
            });
          }
          break;
          
        case 'el-progress':
          // 确保进度条有百分比
          if (enhancedComp.props.percentage === undefined) {
            enhancedComp.props.percentage = 50;
          }
          
          // 确保有默认类型
          if (!enhancedComp.props.type) {
            enhancedComp.props.type = 'line';
          }
          
          // 确保有默认颜色
          if (!enhancedComp.props.color) {
            enhancedComp.props.color = '#409eff';
          }
          break;
          
        case 'el-slider':
          // 确保滑块有默认值
          if (enhancedComp.props.value === undefined && enhancedComp.props.modelValue === undefined) {
            enhancedComp.props.value = 30;
          }
          break;
          
        case 'el-rate':
          // 确保评分组件有默认值
          if (enhancedComp.props.value === undefined && enhancedComp.props.modelValue === undefined) {
            enhancedComp.props.value = 3;
          }
          
          // 确保有最大分值
          if (!enhancedComp.props.max) {
            enhancedComp.props.max = 5;
          }
          break;
          
        case 'el-switch':
          // 确保开关组件有默认值
          if (enhancedComp.props.value === undefined && enhancedComp.props.modelValue === undefined) {
            enhancedComp.props.value = false;
          }
          break;
          
        case 'el-tag':
          // 确保标签有文本
          if (!enhancedComp.props.text && !enhancedComp.props.label) {
            enhancedComp.props.text = '标签';
          }
          
          // 确保有类型
          if (!enhancedComp.props.type) {
            enhancedComp.props.type = '';  // 默认类型
          }
          break;
          
        case 'el-card':
          // 确保卡片有默认阴影
          if (!enhancedComp.props.shadow) {
            enhancedComp.props.shadow = 'always';
          }
          
          // 确保有标题
          if (!enhancedComp.props.header) {
            enhancedComp.props.header = '标题';
          }
          break;
          
        case 'span':
          // 确保span有文本内容
          if (!enhancedComp.props.text && !enhancedComp.props.label) {
            enhancedComp.props.text = '文本标签';
          }
          break;
          
        case 'el-image':
          // 确保图片有src
          if (!enhancedComp.props.src) {
            enhancedComp.props.src = 'https://placehold.co/100x100';
          }
          
          // 确保有填充模式
          if (!enhancedComp.props.fit) {
            enhancedComp.props.fit = 'fill';
          }
          break;
          
        case 'table':
        case 'ew-table':
          // 确保表格组件有datas属性
          if (!enhancedComp.props.datas) {
            if (enhancedComp.setStyle) {
              // 直接使用setStyle作为datas，确保所有配置可用
              enhancedComp.props.datas = enhancedComp.setStyle;
              
              // 确保工具栏配置存在
              if (enhancedComp.props.datas) {
                const datas = enhancedComp.props.datas;
                
                // 确保工具栏配置
                if (datas.showToolbar === undefined) datas.showToolbar = true;
                if (datas.toolbarPosition === undefined) datas.toolbarPosition = 'top';
                if (datas.showRefresh === undefined) datas.showRefresh = true;
                if (datas.showFullscreen === undefined) datas.showFullscreen = true;
                if (datas.showColumnSelect === undefined) datas.showColumnSelect = true;
                
                // 确保操作列配置
                if (datas.showOperationColumn === undefined) datas.showOperationColumn = true;
                if (datas.operationColumnLabel === undefined) datas.operationColumnLabel = '操作';
                if (datas.operationColumnWidth === undefined) datas.operationColumnWidth = '150';
                if (!datas.operationButtons || !Array.isArray(datas.operationButtons) || datas.operationButtons.length === 0) {
                  datas.operationButtons = ['查看', '编辑', '删除'];
                }
                
                // 确保分页配置
                if (datas.showPagination === undefined) datas.showPagination = true;
                if (datas.pageSize === undefined) datas.pageSize = 10;
                if (!datas.pageSizes || !Array.isArray(datas.pageSizes)) {
                  datas.pageSizes = [10, 20, 50, 100];
                }
              }
            } else {
              // 创建默认表格数据
              enhancedComp.props.datas = {
                text: '表格',
                border: true,
                stripe: true,
                showHeader: true,
                highlightCurrentRow: false,
                showIndex: false,
                columns: [
                  { prop: 'date', label: '日期', width: '', sortable: false, align: 'left' },
                  { prop: 'name', label: '姓名', width: '', sortable: false, align: 'left' },
                  { prop: 'address', label: '地址', width: '', sortable: false, align: 'left' }
                ],
                data: [
                  { date: '2023-05-01', name: '张三', address: '北京市' },
                  { date: '2023-05-02', name: '李四', address: '上海市' },
                  { date: '2023-05-03', name: '王五', address: '广州市' }
                ],
                // 确保工具栏配置
                showToolbar: true,
                toolbarPosition: 'top',
                showRefresh: true,
                showFullscreen: true,
                showColumnSelect: true,
                // 确保操作列配置
                showOperationColumn: true,
                operationColumnLabel: '操作',
                operationColumnWidth: '150',
                operationButtons: ['查看', '编辑', '删除'],
                // 确保分页配置
                showPagination: true,
                pageSize: 10,
                pageSizes: [10, 20, 50, 100]
              };
            }
          }
          
          // 设置预览模式为true
          enhancedComp.props.isPreview = true;
          
          console.log('[组件增强] 表格组件处理完成:', enhancedComp);
          break;
      }
      
      // 确保有style对象，并设置基础样式
      enhancedComp.style = enhancedComp.style || {};
      
      // 始终设置绝对定位以与预览保持一致
      if (!enhancedComp.style.position) {
        enhancedComp.style.position = 'absolute';
      }
      
      // 根据组件在列表中的位置设置z-index，确保层叠顺序与预览一致
      if (typeof enhancedComp.style.zIndex === 'undefined') {
        enhancedComp.style.zIndex = index + 1;
      }
      
      // 如果是根级容器且没有宽高，添加默认宽高
      if (!enhancedComp.parentId && (enhancedComp.type === 'div' || enhancedComp.type.startsWith('el-'))) {
        if (!enhancedComp.style.width && !enhancedComp.style.height) {
          enhancedComp.style.width = '100%';
          enhancedComp.style.height = '100%';
        }
      }
      
      // 确保有events对象
      enhancedComp.events = enhancedComp.events || {};
      
      // 递归处理子组件
      if (enhancedComp.children && enhancedComp.children.length > 0) {
        // 过滤掉无效的子组件再处理
        const validChildren = enhancedComp.children.filter((child: any) => child !== null && child !== undefined);
        enhancedComp.children = this.enhanceComponentsForRendering(validChildren);
      } else {
        enhancedComp.children = [];
      }
      
      return enhancedComp;
    }).filter(comp => comp !== null && comp !== undefined); // 过滤掉null和undefined
  }

  /**
   * 获取组件样式
   * 用于在导出和预览中统一组件样式
   * @returns 自定义组件样式CSS
   */
  static getCustomComponentStyles(): string {
    return `
      /* 通用样式 */
      .el-component {
        display: inline-block;
        box-sizing: border-box;
        font-size: 14px;
        color: #606266;
      }
      
      /* 修复按钮样式 */
      .el-button {
        display: inline-block;
        line-height: 1;
        white-space: nowrap;
        cursor: pointer;
        background: #fff;
        border: 1px solid #dcdfe6;
        color: #606266;
        text-align: center;
        box-sizing: border-box;
        outline: none;
        margin: 0;
        transition: .1s;
        font-weight: 500;
        padding: 9px 15px;
        font-size: 14px;
        border-radius: 4px;
      }
      
      .el-button--primary {
        color: #fff;
        background-color: #409eff;
        border-color: #409eff;
      }
      
      .el-button--success {
        color: #fff;
        background-color: #67c23a;
        border-color: #67c23a;
      }
      
      .el-button--warning {
        color: #fff;
        background-color: #e6a23c;
        border-color: #e6a23c;
      }
      
      .el-button--danger {
        color: #fff;
        background-color: #f56c6c;
        border-color: #f56c6c;
      }
      
      .el-button--info {
        color: #fff;
        background-color: #909399;
        border-color: #909399;
      }
      
      /* 输入框修复 */
      .el-input {
        --el-input-height: 32px;
        position: relative;
        display: inline-flex;
        width: 100%;
        box-sizing: border-box;
        vertical-align: middle;
      }
      
      .el-input__inner {
        -webkit-appearance: none;
        background-color: #fff;
        background-image: none;
        border-radius: 4px;
        border: 1px solid #dcdfe6;
        box-sizing: border-box;
        color: #606266;
        display: inline-block;
        font-size: inherit;
        height: var(--el-input-height);
        line-height: var(--el-input-height);
        outline: none;
        padding: 0 15px;
        width: 100%;
      }
      
      /* 开关组件修复 */
      .el-switch {
        position: relative;
        display: inline-flex;
        align-items: center;
        height: 32px;
        line-height: 32px;
        font-size: 14px;
        cursor: pointer;
      }
      
      .el-switch__core {
        margin: 0;
        display: inline-block;
        position: relative;
        width: 40px;
        height: 20px;
        border: 1px solid #dcdfe6;
        outline: none;
        border-radius: 10px;
        box-sizing: border-box;
        background: #dcdfe6;
        cursor: pointer;
        transition: border-color .3s, background-color .3s;
      }
      
      .el-switch__core:after {
        content: "";
        position: absolute;
        top: 1px;
        left: 1px;
        border-radius: 100%;
        transition: all .3s;
        width: 16px;
        height: 16px;
        background-color: #fff;
      }
      
      .el-switch.is-checked .el-switch__core {
        background-color: #409eff;
        border-color: #409eff;
      }
      
      .el-switch.is-checked .el-switch__core:after {
        left: 21px;
      }
      
      /* 确保布局一致性 */
      .design-container {
        position: relative;
        width: 100%;
        height: 100%;
        background-color: #fff;
      }
      
      /* 确保组件定位与预览一致 */
      div[data-component-id], 
      span[data-component-id],
      .el-switch, .el-slider, .el-rate, .el-tag, 
      .el-radio, .el-checkbox, .el-button, .el-input, 
      .el-card, .el-radio-group, .el-checkbox-group, 
      .el-progress, .el-image {
        position: absolute;
      }
      
      /* 修复单选框和复选框样式 */
      .el-radio, .el-checkbox {
        margin-right: 20px;
        display: inline-flex !important;
        align-items: center;
        visibility: visible !important;
        opacity: 1 !important;
        width: auto !important;
        height: auto !important;
        position: relative !important;
      }
      
      .el-radio__input, .el-checkbox__input {
        display: inline-flex !important;
        visibility: visible !important;
        opacity: 1 !important;
        margin-right: 5px;
        line-height: 1;
      }
      
      /* 确保单选框圆圈显示 */
      .el-radio__inner {
        position: relative;
        display: inline-block;
        width: 14px;
        height: 14px;
        background-color: #fff;
        border-radius: 50%;
        border: 1px solid #dcdfe6;
        box-sizing: border-box;
      }
      
      .el-radio__inner::after {
        content: "";
        width: 4px;
        height: 4px;
        border-radius: 50%;
        background-color: #fff;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%) scale(0);
        transition: transform .15s ease-in;
      }
      
      .el-radio.is-checked .el-radio__inner {
        background-color: #409eff;
        border-color: #409eff;
      }
      
      .el-radio.is-checked .el-radio__inner::after {
        transform: translate(-50%, -50%) scale(1);
      }
      
      /* 复选框勾选标记 */
      .el-checkbox__inner {
        position: relative;
        display: inline-block;
        width: 14px;
        height: 14px;
        background-color: #fff;
        border: 1px solid #dcdfe6;
        border-radius: 2px;
        box-sizing: border-box;
      }
      
      .el-checkbox__inner::after {
        box-sizing: content-box;
        content: "";
        border: 1px solid #fff;
        border-left: 0;
        border-top: 0;
        height: 7px;
        left: 4px;
        position: absolute;
        top: 1px;
        transform: rotate(45deg) scaleY(0);
        width: 3px;
        transition: transform .15s ease-in .05s;
        transform-origin: center;
      }
      
      .el-checkbox.is-checked .el-checkbox__inner {
        background-color: #409eff;
        border-color: #409eff;
      }
      
      .el-checkbox.is-checked .el-checkbox__inner::after {
        transform: rotate(45deg) scaleY(1);
      }
      
      /* 单选框组和复选框组内的标签元素修复 */
      .el-radio-group > label,
      .el-checkbox-group > label {
        width: auto !important;
        height: auto !important;
        position: relative !important;
        display: flex !important;
        align-items: center !important;
        margin-right: 10px !important;
      }
    `;
  }
} 